package com.maltys.dp.backpack;

/**
 * 377. 组合总和 Ⅳ
 * 给你一个由 不同 整数组成的数组 nums ，和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。
 * 题目数据保证答案符合 32 位整数范围。
 *
 * @author malty
 */
public class CombinationSumIv {
    public static void main(String[] args) {
        CombinationSumIv combinationSumIv = new CombinationSumIv();
        int combinationSum4 = combinationSumIv.combinationSum4(new int[]{1, 2, 3}, 4);
        System.out.println(combinationSum4);
    }

    public int combinationSum4(int[] nums, int target) {
        int[][] dp = new int[nums.length + 1][target + 1];
        for (int i = 0; i < dp.length; i++) {
            dp[i][0] = 1;
        }
        for (int j = 0; j <= target; j++) {
            for (int i = 1; i <= nums.length; i++) {
                for (int k = i; k > 0; k--) {
                    if (j >= nums[k - 1]) {
                        dp[i][j] += dp[i][j - nums[k - 1]];
                    }
                }
            }
        }
        return dp[nums.length][target];
    }
    public int combinationSum4V2(int[] nums, int target) {
        int[] dp = new int[target + 1];
        dp[0] = 1;
        for (int i = 1; i <= target; i++) {
            for (int j = 0; j < nums.length; j++) {
                if (i >= nums[j]) {
                    dp[i] += dp[i - nums[j]];
                }
            }
        }
        return dp[target];
    }
}
